package com.zq.server.api.service.impl;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zq.common.constant.NumberConstants;
import com.zq.common.core.domain.Result;
import com.zq.common.core.domain.entity.UserInfo;
import com.zq.common.core.redis.RedisCache;
import com.zq.common.exception.base.BaseException;
import com.zq.common.utils.SecurityUtils;
import com.zq.common.utils.StringUtils;
import com.zq.common.utils.date.DateFormatter;
import com.zq.server.api.dao.ActivityMapper;
import com.zq.server.api.dao.GroupMapper;
import com.zq.server.api.dao.UserInfoMapper;
import com.zq.server.api.domain.dto.PublishActivityDto;
import com.zq.server.api.domain.entity.ApiActivity;
import com.zq.server.api.domain.entity.ApiGroup;
import com.zq.server.api.service.ApiActivityService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 活动服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ActivityServiceImpl implements ApiActivityService {
    private static final String TIME = "TIME";
    private final UserInfoMapper userInfoMapper;
    private final ActivityMapper activityMapper;
    private final GroupMapper groupMapper;
    private final RedisCache redisCache;

    /**
     * 获取活动信息列表，并对活动时间进行格式化转换
     * 
     * @param city 活动信息参数
     * @return 格式化后的活动信息列表
     */
    public List<ApiActivity> ListActivityInfo(String city) {
        // 获取活动信息列表
        List<ApiActivity> activities = activityMapper.getActivities(city);
        // 返回格式化后的活动信息列表
        return activities;
    }

    /**
     * 发布活动
     *
     * @param publishActivityDto 发布活动的参数对象
     * @return 是否成功发布活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean publishActivity(PublishActivityDto publishActivityDto) {
        UserInfo user = SecurityUtils.getWeChatUser().getUser();
        // 给默认字段进行初始化赋值
        if (StringUtils.isEmpty(publishActivityDto.getIsCandidate())) {
            // 是否候补
            publishActivityDto.setIsCandidate(NumberConstants.ONE_);
        }
        // 插入活动
        ApiActivity activity = null;
        try {
            activity = saveActivity(user, publishActivityDto);
        } catch (ParseException e) {
            throw new BaseException("插入活动失败");
        }
        // 插入组
        Boolean responseSave = saveGroupList(user, publishActivityDto, activity);
        updateActivityListByTime(activity);
        return responseSave;
    }

    /**
     * 根据 时间 地址 查询活动集合
     *
     * @param time
     * @param address
     * @return com.zq.common.core.domain.Result
     * @作者 Caige
     * @日期 2024.3.24 16:29
     * @Description
     */
    @Override
    public Result getActivityListByTimeAndByAddress(String time, String city) {
        // 解析时间 开始时间和结束时间 or 开始时间
        Map<String, Object> backTimes = DateFormatter.parseDateRange(time);
        if (backTimes.isEmpty() || backTimes.size() >= NumberConstants.THREE_) {
            log.error("日期字符串解析失败 ");
            throw new BaseException("系统异常");
        }
        // 只有开始日期
        if (backTimes.size() == NumberConstants.ONE_) {
            String startTime = backTimes.get("startTime").toString();
            if (StringUtils.isBlank(startTime) || startTime.length() < NumberConstants.FOUR_) {
                log.error("开始日期字符串解析失败 ");
                throw new BaseException("系统异常");
            }
            List<ApiActivity> activityByTimeList = activityMapper.getActivityByTime(startTime, city);
            return Result.success(activityByTimeList);
        }
        // 存在开始日期和结束日期
        if (backTimes.size() == NumberConstants.TWO_) {
            String startTime = backTimes.get("startTime").toString();
            String endTime = backTimes.get("endTime").toString();
            if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)
                || startTime.length() < NumberConstants.FOUR_ || endTime.length() < NumberConstants.FOUR_) {
                log.error("结束日期字符串解析失败 ");
                throw new BaseException("系统异常");
            }
            List<ApiActivity> ActivityListByTimeAndByAddress =
                activityMapper.getActivityListByTimeAndByAddress(startTime, endTime, city);
            return Result.success(ActivityListByTimeAndByAddress);
        }
        return null;
    }

    /**
     * 获取用户参与过的集合
     *
     * @return com.zq.common.core.domain.Result
     * @作者 Caige
     * @日期 2024.3.27 13:14
     */
    @Override
    public List<ApiActivity> getUserPlayActivityList() {
      return  activityMapper.getUserPlayActivityList(SecurityUtils.getWechatUserId());
    }

    /**
     * 删除对应
     */
    public void updateActivityListByTime(ApiActivity param) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedTime = param.getAStarttime().format(formatter);
        if (redisCache.hasKey(formattedTime + TIME)) {
            redisCache.deleteObject(formattedTime + TIME);
        }
    }

    /**
     * 插入活动
     *
     * @param user 用户信息
     * @param params 发布活动的参数对象
     * @return 插入的活动对象
     */
    private ApiActivity saveActivity(UserInfo user, PublishActivityDto params) throws ParseException {
        Map<String, Object> map = DateFormatter.convertDateTimeString(params.getActivityTime());
        LocalDateTime startTime = (LocalDateTime)map.get("startTime");
        LocalDateTime endTime = (LocalDateTime)map.get("endTime");
        String activityTime = map.get("activityTime").toString();
        ApiActivity activityBuilder =
            ApiActivity.builder().aTitle(params.getTitle()).aStarttime(startTime).aEndtime(endTime).aAnnouncement("无")
                .aDescription(params.getDescription()).aImages(params.getImages()).aCreatoropenid(user.getId())
                .aCreatorimage(user.getUHeadportrait()).aApplyOverTime(startTime.plusHours(params.getApplyOverTime()))
                .aState(NumberConstants.ONE_).aCreationtime(LocalDateTime.now()).aCreatorname(user.getUName())
                .aUpdatetime(LocalDateTime.now()).aAddress(params.getAddress())
                .latitude(Double.valueOf(params.getLatitude())).longitude(Double.valueOf(params.getLongitude()))
                .city(params.getCity()).activity_time(activityTime).build();
        activityMapper.saveActivity(activityBuilder);
        return activityBuilder;
    }

    /**
     * 添加组
     *
     * @param user 用户信息
     * @param params 发布活动的参数对象
     * @param activity 活动对象
     */
    private Boolean saveGroupList(UserInfo user, PublishActivityDto params, ApiActivity activity) {
        List<ApiGroup> groupList = new ArrayList();
        ApiGroup build = ApiGroup.builder().gActivityid(activity.getId()).gName("qqq").gUserId(user.getId())
            .gCreationtime(LocalDateTime.now()).gUpdatetime(LocalDateTime.now()).gGroupNumber(params.getGroupNumber())
            .gStatus(NumberConstants.ONE).amount(params.getPersonAmountNumber()).build();
        groupList.add(build);
        Boolean responseSave = groupMapper.saveGroupList(groupList);
        return responseSave;
    }
}
